/* -------------------------------------------------------------------------
 *
 * pgstat_bgwriter.c
 *	  背景写入器统计的实现。
 *
 * 本文件包含背景写入器统计的实现。它与pgstat.c分开，以强制统计访问/存储实现与各类型统计的细节之间的界限。
 *
 * Copyright (c) 2001-2022, PostgreSQL Global Development Group
 *
 * IDENTIFICATION
 *	  src/backend/utils/activity/pgstat_bgwriter.c
 * -------------------------------------------------------------------------
 */

#include "postgres.h"

#include "utils/pgstat_internal.h"


PgStat_BgWriterStats PendingBgWriterStats = {0};


/*
 * 报告 bgwriter 统计信息
 */
void pgstat_report_bgwriter(void)
{
	PgStatShared_BgWriter *fc_stats_shmem = &pgStatLocal.shmem->bgwriter;
	static const PgStat_BgWriterStats fc_all_zeroes;

	Assert(!pgStatLocal.shmem->is_shutdown);
	pgstat_assert_is_up();

	/*
	 * 即使什么事情都没有发生，也可以调用此函数。在这种情况下，避免不必要地修改统计条目。
	 */
	if (memcmp(&PendingBgWriterStats, &fc_all_zeroes, sizeof(fc_all_zeroes)) == 0)
		return;

	pgstat_begin_changecount_write(&fc_stats_shmem->changecount);

#define BGWRITER_ACC(fld) fc_stats_shmem->stats.fld += PendingBgWriterStats.fld
	BGWRITER_ACC(buf_written_clean);
	BGWRITER_ACC(maxwritten_clean);
	BGWRITER_ACC(buf_alloc);
#undef BGWRITER_ACC

	pgstat_end_changecount_write(&fc_stats_shmem->changecount);

	/*
	 * 清除统计缓冲区，以便可以重复使用。
	 */
	MemSet(&PendingBgWriterStats, 0, sizeof(PendingBgWriterStats));
}

/*
 * 支持可调用 pgstat* 函数的函数。返回指向 bgwriter 统计结构的指针。
 */
PgStat_BgWriterStats *
pgstat_fetch_stat_bgwriter(void)
{
	pgstat_snapshot_fixed(PGSTAT_KIND_BGWRITER);

	return &pgStatLocal.snapshot.bgwriter;
}

void pgstat_bgwriter_reset_all_cb(TimestampTz fc_ts)
{
	PgStatShared_BgWriter *fc_stats_shmem = &pgStatLocal.shmem->bgwriter;

	/* 查看上述 PgStatShared_BgWriter 的重置协议说明 */
	LWLockAcquire(&fc_stats_shmem->lock, LW_EXCLUSIVE);
	pgstat_copy_changecounted_stats(&fc_stats_shmem->reset_offset,
									&fc_stats_shmem->stats,
									sizeof(fc_stats_shmem->stats),
									&fc_stats_shmem->changecount);
	fc_stats_shmem->stats.stat_reset_timestamp = fc_ts;
	LWLockRelease(&fc_stats_shmem->lock);
}

void pgstat_bgwriter_snapshot_cb(void)
{
	PgStatShared_BgWriter *fc_stats_shmem = &pgStatLocal.shmem->bgwriter;
	PgStat_BgWriterStats *fc_reset_offset = &fc_stats_shmem->reset_offset;
	PgStat_BgWriterStats fc_reset;

	pgstat_copy_changecounted_stats(&pgStatLocal.snapshot.bgwriter,
									&fc_stats_shmem->stats,
									sizeof(fc_stats_shmem->stats),
									&fc_stats_shmem->changecount);

	LWLockAcquire(&fc_stats_shmem->lock, LW_SHARED);
	memcpy(&fc_reset, fc_reset_offset, sizeof(fc_stats_shmem->stats));
	LWLockRelease(&fc_stats_shmem->lock);

	/* 通过重置偏移量进行补偿 */
#define BGWRITER_COMP(fld) pgStatLocal.snapshot.bgwriter.fld -= fc_reset.fld;
	BGWRITER_COMP(buf_written_clean);
	BGWRITER_COMP(maxwritten_clean);
	BGWRITER_COMP(buf_alloc);
#undef BGWRITER_COMP
}
